<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getNoticeList, getNoticeDetail, createNotice, updateNotice, deleteNotice, updateNoticeStatus, toggleNoticeTop } from '@/api/notice'

// 公告列表数据
const noticeList = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索条件
const searchForm = reactive({
  keyword: '',
  status: null
})

// 公告表单对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增公告')
const noticeForm = reactive({
  id: null,
  title: '',
  content: '',
  status: 1,
  isTop: 0
})
const noticeFormRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 50, message: '标题最多50个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ]
}
const noticeFormRef = ref(null)

// 加载公告列表
const loadNoticeList = async () => {
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status
    }
    
    console.log('API请求参数:', params)
    const res = await getNoticeList(params)
    console.log('API响应结果:', res)
    
    if (res.code === 200) {
      noticeList.value = res.data.records || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取公告列表失败')
    }
  } catch (error) {
    console.error('获取公告列表出错', error)
    ElMessage.error('获取公告列表失败，请稍后重试')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  console.log('搜索条件:', searchForm)
  loadNoticeList()
}

// 处理重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = null
  pagination.currentPage = 1
  loadNoticeList()
}

// 处理分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadNoticeList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadNoticeList()
}

// 打开新增公告对话框
const handleAdd = () => {
  dialogTitle.value = '新增公告'
  noticeForm.id = null
  noticeForm.title = ''
  noticeForm.content = ''
  noticeForm.status = 1
  noticeForm.isTop = 0
  dialogVisible.value = true
}

// 打开编辑公告对话框
const handleEdit = async (row) => {
  try {
    const res = await getNoticeDetail(row.id)
    if (res.code === 200) {
      const notice = res.data
      dialogTitle.value = '编辑公告'
      noticeForm.id = notice.id
      noticeForm.title = notice.title
      noticeForm.content = notice.content
      noticeForm.status = notice.status
      noticeForm.isTop = notice.isTop
      dialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取公告详情失败')
    }
  } catch (error) {
    console.error('获取公告详情出错', error)
    ElMessage.error('获取公告详情失败，请稍后重试')
  }
}

// 切换公告状态
const handleStatusChange = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '发布' : '下架'
  
  ElMessageBox.confirm(
    `确认要${statusText}该公告吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await updateNotice({
          id: row.id,
          status: newStatus
        })
        
        if (res.code === 200) {
          ElMessage.success(`${statusText}成功`)
          loadNoticeList()
        } else {
          ElMessage.error(res.message || `${statusText}失败`)
          row.status = row.status === 1 ? 1 : 0
        }
      } catch (error) {
        console.error('更新公告状态出错', error)
        ElMessage.error(`${statusText}失败，请稍后重试`)
        row.status = row.status === 1 ? 1 : 0
      }
    })
    .catch(() => {
      row.status = row.status === 1 ? 1 : 0
    })
}

// 处理置顶/取消置顶
const handleToggleTop = async (row) => {
  const newIsTop = row.isTop === 1 ? 0 : 1
  const topText = newIsTop === 1 ? '置顶' : '取消置顶'
  
  try {
    const res = await updateNotice({
      id: row.id,
      isTop: newIsTop
    })
    
    if (res.code === 200) {
      ElMessage.success(`${topText}成功`)
      loadNoticeList()
    } else {
      ElMessage.error(res.message || `${topText}失败`)
    }
  } catch (error) {
    console.error('切换置顶状态出错', error)
    ElMessage.error(`${topText}失败，请稍后重试`)
  }
}

// 查看公告详情
const handleDetail = async (row) => {
  try {
    const res = await getNoticeDetail(row.id)
    if (res.code === 200) {
      const notice = res.data
      ElMessageBox.alert(notice.content, notice.title, {
        confirmButtonText: '确定',
        callback: () => {}
      })
    } else {
      ElMessage.error(res.message || '获取公告详情失败')
    }
  } catch (error) {
    console.error('获取公告详情出错', error)
    ElMessage.error('获取公告详情失败，请稍后重试')
  }
}

// 处理删除公告
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该公告吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await deleteNotice(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          loadNoticeList()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除公告出错', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 提交表单
const submitForm = async () => {
  noticeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (noticeForm.id) {
          // 编辑
          res = await updateNotice(noticeForm)
        } else {
          // 新增
          res = await createNotice(noticeForm)
        }
        
        if (res.code === 200) {
          ElMessage.success(noticeForm.id ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          loadNoticeList()
        } else {
          ElMessage.error(res.message || (noticeForm.id ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error('提交公告表单出错', error)
        ElMessage.error('操作失败，请稍后重试')
      }
    }
  })
}

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已发布'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  loadNoticeList()
})
</script>

<template>
  <div class="notice-manage-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>公告管理</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="公告标题/内容"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select 
            v-model="searchForm.status" 
            placeholder="状态" 
            clearable
            style="width: 120px"
          >
            <el-option label="已发布" :value="1" />
            <el-option label="草稿" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增公告</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="noticeList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column label="标题" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <div class="notice-title">
              <el-tag v-if="scope.row.isTop === 1" type="danger" size="small" style="margin-right: 5px">置顶</el-tag>
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" min-width="220" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button
              type="info"
              size="small"
              @click="handleDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              :type="scope.row.isTop === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleToggleTop(scope.row)"
            >
              {{ scope.row.isTop === 1 ? '取消置顶' : '置顶' }}
            </el-button>
            <el-button
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '发布' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格为空时显示 -->
      <div v-if="noticeList.length === 0" class="empty-list">
        <el-empty description="暂无公告数据" />
      </div>

      <!-- 分页区域 -->
      <div class="pagination-container" v-if="noticeList.length > 0">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 公告表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="noticeFormRef"
        :model="noticeForm"
        :rules="noticeFormRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="noticeForm.title"
            placeholder="请输入公告标题"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="noticeForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="noticeForm.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="置顶" prop="isTop">
          <el-radio-group v-model="noticeForm.isTop">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.notice-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.notice-title {
  display: flex;
  align-items: center;
}

.empty-list {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}
</style> 